//
//  WCInfoEditView.m
//  WC
//
//  Created by 杨鑫 on 15/5/7.
//  Copyright (c) 2015年 智康. All rights reserved.
//

#import "WCInfoEditView.h"
#import "WCMaskView.h"
//
#import "NSString+Utilities.h"
//
#import "Constants.h"
#import "Macros.h"
#import "WSJAnimationTool.h"

@interface WCInfoEditView () <UITextFieldDelegate>

@property (weak, nonatomic) WCMaskView *maskView;
@property (weak, nonatomic) UIView *bgView;

@property (weak, nonatomic) UIButton *cancelBtn;
@property (weak, nonatomic) UIButton *saveBtn;

@end

@implementation WCInfoEditView

- (instancetype)init
{
    self = [super init];
    if (self) {
        _type = WCInfoEditTypeText;
        self.limitLenth = 1000;
        
        [self loadView];
    }
    return self;
}

- (void)loadView
{
    self.backgroundColor = kAppBg;
    self.layer.cornerRadius = 4;
    self.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1
                                                              constant:280];
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self
                                                              attribute:NSLayoutAttributeHeight
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:nil
                                                              attribute:NSLayoutAttributeNotAnAttribute
                                                             multiplier:1
                                                               constant:150];
    [self addConstraints:@[width, height]];
    
    UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280, 45)];
    titleView.textColor = HexRGB(0x333333);
    titleView.font = [UIFont systemFontOfSize:18.0];
    titleView.textAlignment = NSTextAlignmentCenter;
    self.titleLabel = titleView;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(15, 45, 250, 38)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.borderWidth = kOnePX;
    bgView.layer.borderColor = kBorderColor.CGColor;
    bgView.layer.cornerRadius = 5;
    self.bgView = bgView;
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 240, 38)];
    textField.delegate = self;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.returnKeyType = UIReturnKeyDone;
    self.textField = textField;
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 100, 120, 35)];
    cancelBtn.layer.borderWidth = kOnePX;
    cancelBtn.layer.borderColor = kBorderColor.CGColor;
    cancelBtn.layer.cornerRadius = 4;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:kTxtColor forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelTap) forControlEvents:UIControlEventTouchUpInside];
    self.cancelBtn = cancelBtn;
    
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(280-15-120, 100, 120, 35)];
    saveBtn.layer.borderWidth = kOnePX;
    saveBtn.layer.borderColor = kBorderColor.CGColor;
    saveBtn.layer.cornerRadius = 4;
    [saveBtn setTitle:@"确定" forState:UIControlStateNormal];
    [saveBtn setTitleColor:HexRGB(0xe91114) forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveTap) forControlEvents:UIControlEventTouchUpInside];
    self.saveBtn = saveBtn;
    
    [bgView addSubview:textField];
    
    [self addSubview:titleView];
    [self addSubview:bgView];
    [self addSubview:cancelBtn];
    [self addSubview:saveBtn];
}

- (void)showIn:(UIView *)view animated:(BOOL)animated
{
    WCMaskView *maskView = [[WCMaskView alloc] init];
    self.maskView = maskView;
    [maskView addSubview:self];
    [view addSubview:maskView];
    
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:maskView
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0];
    NSLayoutConstraint *vCenter = [NSLayoutConstraint constraintWithItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:maskView
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:-kKeyboardHeight/2.0];
    [maskView addConstraints:@[hCenter, vCenter]];
    
    if (animated) {
        CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        popAnimation.duration = 0.25;
        popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5f, 0.5f, 1.0f)],
                                [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                                [NSValue valueWithCATransform3D:CATransform3DIdentity]];
        popAnimation.keyTimes = @[@0.0f, @0.5f, @1.0f];
        popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                         [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                         [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        [self.layer addAnimation:popAnimation forKey:nil];
    }
    
    [self.textField becomeFirstResponder];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification *note){
        self.bgView.layer.borderColor = kBorderColor.CGColor;
    }];
}

- (void)cancelTap
{
    [self.textField resignFirstResponder];
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.alpha = 0.0;
    } completion:^(BOOL finish){
        [self.maskView removeFromSuperview];
        if (self.cancel) {
            self.cancel();
        }
    }];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)saveTap
{
    if (self.textField.text.length>self.limitLenth) {
        self.bgView.layer.borderColor = [UIColor redColor].CGColor;
        self.saveBtn.enabled = NO;
        /**
         *  添加提醒动画
         */
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.titleLabel.frame;
            frame.origin.y = -45;
            self.titleLabel.frame = frame;
            self.titleLabel.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                NSString *title = self.titleLabel.text;
                self.titleLabel.textColor = [UIColor redColor];
                [UIView animateWithDuration:0.2 animations:^{
                self.titleLabel.text = [NSString stringWithFormat:@"输入长度不得大于%d",self.limitLenth];
                
                CGRect frame = self.titleLabel.frame;
                frame.origin.y = 0;
                self.titleLabel.frame = frame;
                self.titleLabel.alpha = 1;

                } completion:^(BOOL finished) {
                    [UIView animateWithDuration:0.2 delay:1.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                        CGRect frame = self.titleLabel.frame;
                        frame.origin.y = -45;
                        self.titleLabel.frame = frame;
                        self.titleLabel.alpha = 0;
                       
                    } completion:^(BOOL finished) {
                        if (finished) {
                            self.titleLabel.textColor = [UIColor blackColor];
                            [UIView animateWithDuration:0.3 animations:^{
                                self.titleLabel.text = title;
                                CGRect frame = self.titleLabel.frame;
                                frame.origin.y = 0;
                                self.titleLabel.frame = frame;
                                self.titleLabel.alpha = 1;
                                
                                self.saveBtn.enabled = YES;
                            }];
                        }

                    }];
                    
                }];
            }
        }];
        [WSJAnimationTool shakeAnimation:self];
        return;
    }

    BOOL close = self.save(self.textField.text);
    if (close) {
        
        
        [self.textField resignFirstResponder];
        [UIView animateWithDuration:0.25 animations:^{
            self.maskView.alpha = 0.0;
        } completion:^(BOOL finish){
            [self.maskView removeFromSuperview];
        }];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    } else {
        
        self.bgView.layer.borderColor = [UIColor redColor].CGColor;
        [WSJAnimationTool shakeAnimation:self];
    }
}

- (void)setType:(WCInfoEditType)type {
    _type = type;
    if (self.type == WCInfoEditTypeInteger ||self.type == WCInfoEditTypeMoney) {
        _textField.keyboardType = UIKeyboardTypeDecimalPad;
    }

}
#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.type == WCInfoEditTypeMoney) {
        NSMutableString *text = [NSMutableString stringWithString:textField.text];
        [text replaceCharactersInRange:range withString:string];
        if ([text isMoney]) {
            return YES;
        } else if (text.length == 0) {
            return YES;
        }
        
        return NO;
    } else if (self.type == WCInfoEditTypeInteger) {
        NSMutableString *text = [NSMutableString stringWithString:textField.text];
        [text replaceCharactersInRange:range withString:string];
        
        if (text.length == 0) {
            return YES;
        }
        if ([string isEqualToString:@"."]) {
            return YES;
        }
        NSScanner* scan = [NSScanner scannerWithString:text];
        float val;
        return [scan scanFloat:&val] && [scan isAtEnd];
    } else {
        return YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self saveTap];
    return NO;
}

@end
